# -*- coding: utf-8 -*-
#!/usr/bin/env python

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from xml.sax.saxutils import escape

dateFormat = "dd.MM.yyyy"

class AimsEditDlg(QDialog):

    def __init__(self, parent=None, fieldValues=None):
        super(AimsEditDlg, self).__init__(parent)

        labelName            = QLabel("Aim's name:")
        self.editName        = QLineEdit()

        labelDescription     = QLabel("Description:")
        self.editDescription = QTextEdit()

        labelStartpoint      = QLabel("Startpoint:")
        self.editStartpoint  = QDateEdit()
        self.editStartpoint.setDisplayFormat(dateFormat)

        labelDeadline        = QLabel("Deadline:")
        self.editDeadline    = QDateEdit()
        self.editDeadline.setDisplayFormat(dateFormat)

        labelPriority        = QLabel("Priority:")
        self.editPriority    = QSpinBox()
        self.editPriority.setRange(1, 10)
  
        labelUnit            = QLabel("Unit:")
        self.editUnit        = QLineEdit()

        labelEstimation      = QLabel("Estimation:")
        self.editEstimation  = QSpinBox()  
        self.editEstimation.setMinimum(0)

        self.cbMeasurable    = QCheckBox("Measurable")

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                     QDialogButtonBox.Cancel)

        grid = QGridLayout()
        grid.addWidget(labelName, 0, 0)
        grid.addWidget(self.editName, 0, 1)
        grid.addWidget(labelDescription, 1, 0)
        grid.addWidget(self.editDescription, 1, 1)
        grid.addWidget(labelStartpoint, 2, 0)
        grid.addWidget(self.editStartpoint, 2, 1)
        grid.addWidget(labelDeadline, 3, 0)
        grid.addWidget(self.editDeadline, 3, 1)
        grid.addWidget(labelPriority, 4, 0)
        grid.addWidget(self.editPriority, 4, 1)

        grid.addWidget(self.cbMeasurable, 5, 0, 1, 2)

        grid.addWidget(labelUnit, 6, 0)
        grid.addWidget(self.editUnit, 6, 1)
        grid.addWidget(labelEstimation, 7, 0)
        grid.addWidget(self.editEstimation, 7, 1)
        self.editUnit.setEnabled(False)
        self.editEstimation.setEnabled(False)
        
        grid.addWidget(buttonBox, 8, 0, 1, 2)
        self.setLayout(grid)

        self.connect(buttonBox, SIGNAL("accepted()"),
                     self, SLOT("accept()"))
        self.connect(buttonBox, SIGNAL("rejected()"),
                     self, SLOT("reject()"))
        self.connect(self.cbMeasurable, SIGNAL("toggled(bool)"), self.measurabilityChanged)


        self.setWindowTitle("Input aim info:")

        # В зависимости от того, используется диалог для
        # добавления новой цели, или для редактирования существующей,
        # вести он себя будет несколько по-разному:
    
        if fieldValues is not None:
            self.cbMeasurable.setEnabled(False)

            self.editName.setText(fieldValues[0])
            self.editDescription.append(fieldValues[1])
            self.editStartpoint.setDate(QDate.fromString(fieldValues[2], dateFormat))
            self.editDeadline.setDate(QDate.fromString(fieldValues[3], dateFormat))
            self.editPriority.setValue(int(fieldValues[4]))
            if len(fieldValues) == 5:
                self.cbMeasurable.setChecked(False)
                self.editUnit.setEnabled(False)
                self.editEstimation.setEnabled(False)
            elif len(fieldValues) == 7: 
                self.editUnit.setText(fieldValues[5])
                self.editEstimation.setValue(int(fieldValues[6]))
                self.cbMeasurable.setChecked(True)


    def accept(self):

        class EmptyNameError(Exception): pass
        class TimeBoundError(Exception): pass

        name = unicode(self.editName.text())

        try:
            if len(name) == 0:
                raise EmptyNameError, ("Name must be not empty!")
            if self.editStartpoint.date() > self.editDeadline.date():
                raise TimeBoundError, ("Wrond time bounds!")
         
        except EmptyNameError, e:
            QMessageBox.warning(self, "Empty Name Error", unicode(e))
            self.editName.selectAll()
            self.editName.setFocus()
            return
        except TimeBoundError, e:
            QMessageBox.warning(self, "TimeBoundError", unicode(e))
            return

        QDialog.accept(self)

    def measurabilityChanged(self, measurable):
        self.editUnit.setEnabled(measurable)
        self.editEstimation.setEnabled(measurable)

    def getFieldValues(self):
        if self.exec_():
            # Если добавляем конечную, измеряемую цель.
            if self.cbMeasurable.isChecked():
                return (True                                          \
                      ,unicode(self.editName.text())                  \
                      ,escape(unicode(self.editDescription.toPlainText()))    \
                      ,unicode(self.editStartpoint.date().toString(dateFormat)) \
                      ,unicode(self.editDeadline.date().toString(dateFormat))   \
                      ,"%i" % self.editPriority.value()               \
                      ,unicode(self.editUnit.text())                  \
                      ,"%i" % self.editEstimation.value())
            else:
                return (False                                         \
                      ,unicode(self.editName.text())                  \
                      ,unicode(self.editDescription.toPlainText())    \
                      ,unicode(self.editStartpoint.date().toString(dateFormat)) \
                      ,unicode(self.editDeadline.date().toString(dateFormat))   \
                      ,"%i" % self.editPriority.value())               
        else:
            return None


